<?php
namespace app\api\controller\wechat;

use app\admin\model\user\AdminOauth;
use app\common\controller\Admin;
use app\common\controller\ApiBase;
use app\datumdata\model\UserShare;
use app\datumdata\model\UserShareUnit;
use app\datumdata\service\UserShareService;
use app\wechat\service\MiniProgram;
use think\facade\Log;
use think\Request;

class Login extends ApiBase
{
    public function min_programe_do_login(Request $request)
    {
        if($request->isPost())
        {
            $minProgramApp  =  new MiniProgram(get_option("datumdata"));

            $post = $request->post();

            Log::warning("login_post".json_encode($post));
            //用户端 没有 openid
            if(!isset($post['openid']))
            {
                //通过js_cod 获取 session_code 以及用户 open Id
                if(!isset($post['js_code']))
                {
                    $this->error("请获取访问凭证进行操作");
                }else{
                    $sessionCode = $minProgramApp->getCode($post['js_code']);
                    if(isset($sessionCode['session_key']) && isset($sessionCode['openid']))
                    {
                        $post["openid"]   = $sessionCode['openid'];
                        $post['union_id'] = isset($sessionCode['unionid'])?$sessionCode['unionid']:'';
                        $post['session_key'] = $sessionCode['session_key'];
                    }
                   /* $i=0;
                    while ($i<=0)
                    {
                        $sessionCode = $minProgramApp->getCode($post['js_code']);
                        if(isset($sessionCode['session_key']) && isset($sessionCode['openid']))
                        {
                            $post["openid"]   = $sessionCode['openid'];
                            $post['union_id'] = isset($sessionCode['unionid'])?$sessionCode['unionid']:'';
                            $post['session_key'] = $sessionCode['session_key'];
                            break;
                        }
                        if($i>10){
                            break;
                        }
                        $i++;
                    }*/
                }
            }

            $user = AdminOauth::where("openid",$post['openid'])->find();
            $currentTime    = time();
            $expireSeconds  = 24 * 3600 * 7;
            $expireTime     = $currentTime + $expireSeconds;
            $clientIp       = get_client_ip();
            $app            = $minProgramApp->getApp();
            $appid          = isset($post['app_id'])?$post['app_id']:$app['app_id'];
            //手机检测
            if(isset($post['telphone'])){
                //不是明文手机
                if(!cmf_check_mobile($post['telphone']))
                {
                    $minProgramApp->decryptData($post['session_key'],$post['telphone'],$post['iv'],$data);
                    if($data)
                    {
                        $data = json_decode($data,true);
                        $post['telphone'] = $data['phoneNumber'];
                    }else{
                        $post['telphone'] = '';
                    }
                   /* $a = 0;
                    while($a<=10)
                    {
                        $minProgramApp->decryptData($post['session_key'],$post['telphone'],$post['iv'],$data);
                        if($data)
                        {
                            $data = json_decode($data,true);
                            $post['telphone'] = $data['phoneNumber'];
                            break;
                        }else{
                            $post['telphone'] = '';
                        }
                        $a++;
                    }*/
                }
            }else{
                $post['telphone'] = '';
            }
            //用户注册行为
            if($user)
            {
                //拉黑用户
                if($user['status']==0) $this->error("该用户已被禁止登陆！");
                //======================== 其它操作 start =============
                $user['third_party_user_id'] = $user['id'];
                (new UserShareService())->createShare($user);
                //======================= 其它操作 end ===============
                //有效时间内
                if($user['expire_time']>time())
                {
                    //更新手机号
                    if($post['telphone'])
                    {
                        AdminOauth::where("openid",$post['openid'])
                            ->update([
                                "more"            => [
                                    "telphone" => $post['telphone'],
                                    "avatar"   => isset($post['avatar'])?$post['avatar']:''
                                ]
                            ]);
                    }

                    $this->success("登陆成功",'',$user);

                    //过期时间
                }else{
                    //设置token
                    $token          =  $minProgramApp->getAccessToken(true);
                    $minProgramApp->setAccessToken($token['access_token'],$expireSeconds);
                    $accessToken    = isset($post['access_token'])?$post['access_token']:$token['access_token'];
                    //登录次数加+1
                    AdminOauth::where("openid",$post['openid'])->setInc("login_times",1);
                    //修改登录状态
                    AdminOauth::where("openid",$post['openid'])
                        ->update([
                            //最后登录时间
                            "last_login_time" => $currentTime,
                            //token 有效时间
                            "expire_time"     => $expireTime,
                            //最后登录ip 地段
                            "last_login_ip"   => $clientIp,
                            //token
                            "access_token"    => $accessToken,
                            // avatar
                            "more"            => [
                                "telphone" => $post['telphone'],
                                "avatar"   => isset($post['avatar'])?$post['avatar']:''
                            ]
                        ]);
                    $user['last_login_time'] = $currentTime;
                    $user['last_login_ip']   = $clientIp;
                    $user['expire_time']     = $expireTime;
                    $user['expire_seconds']  = $expireSeconds;
                    $user['access_token']    = $accessToken;
                }
            }else{
                /**
                 * 用户注册行为
                 */
                //设置token
                $token          =  $minProgramApp->getAccessToken(true);
                $minProgramApp->setAccessToken($token['access_token'],$expireSeconds);
                $accessToken    = isset($post['access_token'])?$post['access_token']:$token['access_token'];

                $result = AdminOauth::create([
                    "last_login_time" => $currentTime,
                    "expire_time"     => $expireTime,
                    "last_login_ip"   => $clientIp,
                    "access_token"    => $accessToken,
                    "status"          => 1,
                    "nickname"        => isset($post['nickname'])?$post['nickname']:'',
                    "third_party"     => isset($post['third_party'])?$post['third_party']:'',
                    "login_times"     => 1,
                    "app_id"          => $appid,
                    "openid"          => $post["openid"],
                    "union_id"        => $post['union_id'],
                    "more"            => [
                        "telphone" => $post['telphone'],
                        "avatar"   => isset($post['avatar'])?$post['avatar']:''
                    ]
                ]);
                if($result)
                {
                    $user = AdminOauth::where("id",$result['id'])->find();
                    $user['expire_seconds']  = $expireSeconds;
                    //======================== 其它操作 start =============
                    $user['third_party_user_id'] = $user['id'];
                    (new UserShareService())->createShare($user);
                    //======================= 其它操作 end ===============
                    $this->success("登录成功",'',$user);
                }else{
                    $this->error("登录失败");
                }
            }
        }else{
            $this->error("请求错误，请换成‘POST’请求");
        }
    }

    //检测用户是不是真是有效
    public function check_user()
    {
        $openid = $this->request->param("openid");

        if(!$openid) $this->error("openid 不能为空",$this->request->url());

        $user   = (new AdminOauth())->where("openid",$openid)->find();

        $this->success("获取成功",$this->request->url(),$user);
    }
}